﻿using System;
using System.Linq;
using System.Threading.Tasks;
using System.Transactions;
using Elsa.Services.Models;
using HengTong.Model._Admin;
using HengTong.Model.Db.Hr;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using TiaoTaoHelper.Extension.Object;
using TiaoTaoHelper.Wtm.Interfaces;
using TiaoTaoHelper.Wtm.Models;
using TiaoTaoHelper.Wtm.Workflow;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.WorkFlow;

namespace HengTong.ViewModel.Person.SysPersonUpdateBillVms;

public partial class SysPersonUpdateBillVm
{
    [WorkflowOperation("驳回", "将单据状态设置为草稿", "信息更新")]
    public async Task Reject(ActivityExecutionContext context)
    {
        Entity.BillStatus = BillStatus.草稿;
        if (Entity is IBasePoco poco)
        {
            poco.UpdateTime = DateTime.Now;
            DC.UpdateProperty(Entity, x => x.UpdateTime);
            if (context.Input is WtmApproveInput input)
            {
                poco.UpdateBy = input.CurrentUser?.ITCode ?? "workflow";
                DC.UpdateProperty(Entity, x => x.UpdateBy);
            }
        }

        DC.UpdateProperty(Entity, x => x.BillStatus);
        await DC.SaveChangesAsync();
    }

    [WorkflowOperation("取消", "将流程状态设置为取消", "信息更新")]
    public async Task Cancel(ActivityExecutionContext context)
    {
        if (Entity is IBasePoco poco)
        {
            poco.UpdateTime = DateTime.Now;
            DC.UpdateProperty(Entity, x => x.UpdateTime);
            if (context.Input is WtmApproveInput input)
            {
                poco.UpdateBy = input.CurrentUser?.ITCode ?? "workflow";
                DC.UpdateProperty(Entity, x => x.UpdateBy);
            }
        }

        if (Entity is IBill bill)
        {
            bill.WorkflowStatus = WorkflowStatus.已取消;
            DC.UpdateProperty(Entity, x => x.WorkflowStatus);
        }

        await DC.SaveChangesAsync();
    }


    /// <summary>
    /// 更新档案 - 仅更新主表信息
    /// </summary>
    [WorkflowOperation("更新档案", "将更新单据数据更新到人员档案", "信息更新")]
    public async Task UpdatePersonArchive(ActivityExecutionContext context)
    {
        // 获取 logger
        var scope = Wtm.ServiceProvider.CreateScope();
        var _logger = scope.ServiceProvider.GetRequiredService<ILogger<SysPersonUpdateBillVm>>();

        string currentUser = "workflow";
        if (context.Input is WtmApproveInput input)
        {
            currentUser = input.CurrentUser?.ITCode ?? "workflow";
        }

        using var transactionScope = new TransactionScope(
            TransactionScopeOption.Required,
            new TransactionOptions
            {
                IsolationLevel = IsolationLevel.ReadCommitted,
                Timeout = TimeSpan.FromMinutes(10)
            },
            TransactionScopeAsyncFlowOption.Enabled);

        try
        {
            _logger.LogInformation("档案更新流程结束事件开始");
            _logger.LogInformation("开始更新人员档案，单据ID: {EntityId}, 工号: {StaffNo}, 操作人: {CurrentUser}, 时间: {Time}",
                Entity?.ID, Entity?.StaffNo, currentUser, DateTime.Now);

            if (Entity == null || Entity.ID == Guid.Empty)
            {
                _logger.LogWarning("更新单据不存在，EntityId: {EntityId}", Entity?.ID);
                MSD.AddModelError(" ", "更新单据不存在");
                return;
            }

            // 查找目标人员档案
            var targetPerson = await DC.Set<SysPerson>()
                .Where(x => x.GetType() == typeof(SysPerson))
                .AsNoTracking()
                .FirstOrDefaultAsync(p => p.StaffNo == Entity.StaffNo);

            if (targetPerson == null)
            {
                _logger.LogWarning("未找到工号为 {StaffNo} 的人员档案，单据ID: {EntityId}", Entity.StaffNo, Entity.ID);
                MSD.AddModelError(" ", $"未找到工号为 {Entity.StaffNo} 的人员档案");
                return;
            }

            var targetPersonId = targetPerson.ID;
            var currentTime = DateTime.Now;

            _logger.LogInformation("找到目标人员档案，PersonId: {PersonId}, StaffNo: {StaffNo}", targetPersonId, Entity.StaffNo);

            // 清除附件信息
            Entity.IdCardBackPhoto = null;
            Entity.IdCardFrontPhoto = null;
            Entity.Photo = null;
            Entity.Resume = null;
            Entity.Order = targetPerson.Order ?? 99;

            // 复制更新数据到目标档案
            Entity.CloneMatchingProperties(targetPerson);
            targetPerson.ID = targetPersonId;
            targetPerson.UpdateTime = currentTime;
            targetPerson.UpdateBy = currentUser;

            // 更新主表
            DC.Set<SysPerson>().Update(targetPerson);
            _logger.LogInformation("更新主表数据完成，PersonId: {PersonId}", targetPersonId);

            // 条件更新FrameworkUser的手机号和照片
            var frameworkUser = await DC.Set<FrameworkUser>()
                .FirstOrDefaultAsync(u => u.ITCode == Entity.StaffNo);

            if (frameworkUser != null)
            {
                bool needUpdate = false;

                // 检查手机号是否需要更新
                if (frameworkUser.CellPhone != Entity.Phone)
                {
                    _logger.LogInformation("更新手机号，从 {OldPhone} 到 {NewPhone}, StaffNo: {StaffNo}",
                        frameworkUser.CellPhone, Entity.Phone, Entity.StaffNo);
                    frameworkUser.CellPhone = Entity.Phone;
                    needUpdate = true;
                }

                // 检查照片是否需要更新
                if (frameworkUser.PhotoId != Entity.PhotoId)
                {
                    _logger.LogInformation("更新照片ID，从 {OldPhotoId} 到 {NewPhotoId}, StaffNo: {StaffNo}",
                        frameworkUser.PhotoId, Entity.PhotoId, Entity.StaffNo);
                    frameworkUser.PhotoId = Entity.PhotoId;
                    needUpdate = true;
                }

                if (needUpdate)
                {
                    DC.Set<FrameworkUser>().Update(frameworkUser);
                    await Wtm.RemoveUserCache(Entity.StaffNo);
                    _logger.LogInformation("FrameworkUser更新完成并清除缓存，StaffNo: {StaffNo}", Entity.StaffNo);
                }
                else
                {
                    _logger.LogInformation("FrameworkUser无需更新，StaffNo: {StaffNo}", Entity.StaffNo);
                }
            }
            else
            {
                _logger.LogWarning("未找到对应的FrameworkUser，StaffNo: {StaffNo}", Entity.StaffNo);
            }

            // 更新单据状态
            Entity.WorkflowStatus = WorkflowStatus.已完成;
            DC.UpdateProperty(Entity, x => x.WorkflowStatus);

            await DC.SaveChangesAsync();
            transactionScope.Complete();

            _logger.LogInformation("成功更新人员档案，StaffNo: {StaffNo}, WorkflowStatus: {WorkflowStatus}",
                Entity.StaffNo, Entity.WorkflowStatus);
        }
        catch (Exception e)
        {
            _logger.LogError(e, "更新人员档案失败，单据ID: {EntityId}, 工号: {StaffNo}, 操作人: {CurrentUser}, 时间: {Time}",
                Entity?.ID, Entity?.StaffNo, currentUser, DateTime.Now);
            MSD.AddModelError(" ", $"更新人员档案失败: {e.Message}");
        }
    }
}